package com.dc.netty;


import com.alibaba.fastjson.JSON;
import com.dc.enums.ServiceIdType;
import com.dc.model.Device;
import com.dc.model.LockResponseParams;
import com.dc.mqtt.MqttService;
import com.dc.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * netty队列监听类
 */
@Component
@ChannelHandler.Sharable
//@Slf4j
public class ServerChannelHandler extends ServerChannelAbstract {

    @Resource
    MqttService mqttService;

    /**
     * 拿到传过来的msg数据，开始处理
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
        ByteBuf data = (ByteBuf) msg;
        byte[] barray = new byte[data.readableBytes()];
        data.readBytes(barray);
        System.out.println("十六进制:" + ByteUtil.bytesToHex(barray));
        for (byte b : barray) {
            System.out.println("二进制:" + Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));
        }
        //TODO 保存当前channel客户端信息
        TcpServer.map.put("唯一标识", ctx.channel());
        //TODO 应答数据
        byte[] b = new byte[2];
        b[0] = (byte) 0xAA;
        b[1] = (byte) 0xFF;
        //TODO 发送内部mqtt(解析系统需要的数据)
        Device device = new Device();
        device.setSerialNumber("设备编码");
        device.setDeviceStatus(0); //设备状态
        mqttService.sendToMqtt(LockResponseParams.getSubTopic(ServiceIdType.FIRE_SERVICE_ID.getType()), 2, JSON.toJSONString(device));
        //应答
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer(b)).syncUninterruptibly();
    }


}
